import { LANG, TAGS_VIEW } from '@/constant'
import { getItem, setItem } from '@/utils/storage'
import router from '@/router'
const state = {
  sidebarOpened: true,
  language: getItem(LANG) || 'zh',
  tagsViewList: getItem(TAGS_VIEW) || []
}

const mutations = {
  triggerSidebarOpened(state) {
    state.sidebarOpened = !state.sidebarOpened
  },
  changeLanguage(state, language) {
    state.language = language
    setItem(LANG, language)
  },
  /**
    * 添加 tags
    */
  addTagsViewList(state, tag) {
    const isFind = state.tagsViewList.find(item => {
      return item.path === tag.path
    })
    // 处理重复
    if (!isFind) {
      state.tagsViewList.push(tag)
      setItem(TAGS_VIEW, state.tagsViewList)
    }
  },
  /**
* 国际化解决方案时 tag 修改 title
*/
  changeTagsView(state, { index, tag }) {
    state.tagsViewList[index] = tag
    setItem(TAGS_VIEW, state.tagsViewList)
  },
  deleteOneTag(state, index) {
    state.tagsViewList.splice(index, 1)
    setItem(TAGS_VIEW, state.tagsViewList)
  },
  closeCurrent(state, path) {
    if (state.tagsViewList.length !== 1) {
      state.tagsViewList.filter((item, index) => {
        if (item.path === path) {
          // 跳转到前一个页面
          router.push(state.tagsViewList[index - 1].path)
          state.tagsViewList.splice(index, 1)
          setItem(TAGS_VIEW, state.tagsViewList)
        }
        return item.path === path
      })
    }
  },
  closeRight(state, index) {
    if (index !== state.tagsViewList.length - 1) {
      state.tagsViewList.splice(index + 1)
      setItem(TAGS_VIEW, state.tagsViewList)
    }
  },
  closeOther(state, index) {
    if (state.tagsViewList.length !== 1) {
      state.tagsViewList = state.tagsViewList.splice(index, 1)
      setItem(TAGS_VIEW, state.tagsViewList)
    }
  }

}

const actions = {

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
